package controllers

import javax.inject.Inject
import org.joda.time.DateTime
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import tool.{FormTool, Tool}
import utils.Utils

import java.io.File
import implicits.Implicits._
import org.apache.commons.io.FileUtils
import os.Path

/**
 * Created by yz on 2019/2/18
 */
class ToolController @Inject()(cc: ControllerComponents, tool: Tool) extends AbstractController(cc) {

  def getServerTime = Action { implicit request =>
    val time = new DateTime()
    val timeStr = Utils.dataTime2String(time)
    Ok(Json.obj("time"->timeStr))
  }

  def getFileData = Action { implicit request =>
    val data = FormTool.fileNameForm.bindFromRequest().get
    val file = new File(tool.dataDir, data.fileName)
    val maps = file.xlsxLines().lineMap
    Ok(Json.toJson(maps))
  }

  def openLiterPdf = Action { implicit request =>
    val data = FormTool.indexForm.bindFromRequest().get
    val path = Path(tool.dataDir.getAbsolutePath)
    val pdfPath=os.walk(path).filter(os.isFile).filter(_.baseName.startsWith(s"${data.index}-")).head
    val bytes=os.read.bytes(pdfPath)
    Ok(bytes).as("application/pdf")
  }

}
